package com.archermind.boc.xml.converter;

import com.archermind.boc.domain.Transport;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class TransportConverter implements Converter {

	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
		Transport transport = (Transport) source;
		String ip = transport.getIp();
		if (ip != null)
			writer.addAttribute("ip", ip);
		int port = transport.getPort();
		if (port >= 0)
			writer.addAttribute("port", port + "");
		String content = transport.getContent();
		if (content != null)
			writer.setValue(content);
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		Transport transport = new Transport();
		String ip = null;
		int port = 0;
		String portStr = null;
		ip = reader.getAttribute("ip");
		if (ip != null)
			transport.setIp(ip);
		portStr = reader.getAttribute("port");
		if (portStr != null && Util.isNumric(portStr))
			transport.setPort(Integer.parseInt(portStr));
		transport.setContent(reader.getValue());
		return transport;
	}

	public boolean canConvert(Class type) {
		return type.equals(Transport.class);
	}

}
